package bkhech.generator.mp.util;

import bkhech.generator.mp.config.GenConfig;
import bkhech.generator.mp.constant.GenConstants;
import bkhech.generator.mp.domain.GenTable;
import bkhech.generator.mp.domain.GenTableColumn;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.VelocityContext;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * 模板处理工具类
 *
 * @author ruoyi
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class VelocityUtils {

    /**
     * 项目空间路径
     */
    private static final String PROJECT_PATH = "main/java";

    /**
     * mybatis空间路径
     */
    private static final String MYBATIS_PATH = "main/resources";

    /**
     * 设置模板变量信息
     *
     * @return 模板列表
     */
    public static VelocityContext prepareContext(GenTable genTable) {
        String moduleName = genTable.getModuleName();
        String businessName = genTable.getBusinessName();
        String packageName = genTable.getPackageName();
        String functionName = genTable.getFunctionName();

        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("tableName", genTable.getTableName());
        velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
        velocityContext.put("ClassName", genTable.getClassName());
        velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
        velocityContext.put("moduleName", genTable.getModuleName());
        velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
        velocityContext.put("businessName", genTable.getBusinessName());
        velocityContext.put("basePackage", getPackagePrefix(packageName));
        velocityContext.put("packageName", packageName);
        velocityContext.put("author", genTable.getFunctionAuthor());
        velocityContext.put("datetime", DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        velocityContext.put("pkColumn", genTable.getPkColumn());
        velocityContext.put("importList", getImportList(genTable));
        velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
        velocityContext.put("columns", genTable.getColumns());
        velocityContext.put("table", genTable);
        return velocityContext;
    }


    /**
     * 获取模板信息
     *
     * @return 模板列表
     */
    public static List<String> getTemplateList() {
        String vmTemplateResourcePackageName = GenConstants.VM_TEMPLATE_RESOURCE_PACKAGE_NAME;
        if (StrUtil.isNotBlank(GenConfig.vmTemplateResourcePackageName)) {
            vmTemplateResourcePackageName = GenConfig.vmTemplateResourcePackageName;
        }
        System.err.println("vmTemplateResourcePackageName = " + vmTemplateResourcePackageName);
        List<String> templates = new ArrayList<>();
        templates.add(vmTemplateResourcePackageName + "/java/domain.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/vo.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/bo.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/mapper.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/service.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/serviceImpl.java.vm");
        templates.add(vmTemplateResourcePackageName + "/java/controller.java.vm");
        templates.add(vmTemplateResourcePackageName + "/xml/mapper.xml.vm");
        return templates;
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String template, GenTable genTable, String genPath) {
        // 文件名称
        String fileName = "";
        // 包路径
        String packageName = genTable.getPackageName();
        // 模块名
        String moduleName = genTable.getModuleName();
        // 大写类名
        String className = genTable.getClassName();

        String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
        final String configMapperXmlNamespace = GenConfig.extra.mapperXmlNamespace;
        String mapperXmlNamespace = GenConstants.MAPPER_XML_NAMESPACE;
        if (StrUtil.isNotBlank(configMapperXmlNamespace)) {
            mapperXmlNamespace = configMapperXmlNamespace;
        }
        String mybatisPath = MYBATIS_PATH + "/" + mapperXmlNamespace +  "/" + moduleName;

        if (template.contains("domain.java.vm")) {
            fileName = StrUtil.format("{}/domain/{}.java", javaPath, className);
            // 特殊处理1：存在自定义 domain 路径，直接返回
            if (StrUtil.isNotBlank(GenConfig.extra.genPathOfDomain)) {
                fileName = StrUtil.format("{}/{}.java", GenConfig.extra.genPathOfDomain, className);
                return fileName;
            }
        }
        if (template.contains("vo.java.vm")) {
            fileName = StrUtil.format("{}/domain/vo/{}Vo.java", javaPath, className);
        }
        if (template.contains("bo.java.vm")) {
            fileName = StrUtil.format("{}/domain/bo/{}Bo.java", javaPath, className);
        }
        if (template.contains("mapper.java.vm")) {
            final String configMapperPackageName = GenConfig.extra.mapperPackageName;
            String mapperPackageName = GenConstants.MAPPER_PACKAGE_NAME;
            if (StrUtil.isNotBlank(configMapperPackageName)) {
                mapperPackageName = configMapperPackageName;
            }
            fileName = StrUtil.format("{}/{}/{}Mapper.java", javaPath, mapperPackageName, className);
        } else if (template.contains("service.java.vm")) {
            fileName = StrUtil.format("{}/service/{}Service.java", javaPath, className);
        } else if (template.contains("serviceImpl.java.vm")) {
            fileName = StrUtil.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
        } else if (template.contains("controller.java.vm")) {
            fileName = StrUtil.format("{}/controller/{}Controller.java", javaPath, className);
        } else if (template.contains("mapper.xml.vm")) {
            fileName = StrUtil.format("{}/{}Mapper.xml", mybatisPath, className);
        }

        if (StrUtil.isBlank(genPath) || StringUtils.equals(genPath, "/")) {
            return System.getProperty("user.dir") + File.separator + "src" + File.separator + fileName;
        }

        return genPath + File.separator + fileName;
    }

    /**
     * 根据列类型获取导入包
     *
     * @param genTable 业务表对象
     * @return 返回需要导入的包列表
     */
    public static HashSet<String> getImportList(GenTable genTable) {
        List<GenTableColumn> columns = genTable.getColumns();
        HashSet<String> importList = new HashSet<>();
        for (GenTableColumn column : columns) {
            if (!column.isSuperColumn() && GenConstants.TYPE_DATE.equals(column.getJavaType())) {
                importList.add("java.util.Date");
            } else if (!column.isSuperColumn() && GenConstants.TYPE_BIGDECIMAL.equals(column.getJavaType())) {
                importList.add("java.math.BigDecimal");
            }
        }
        return importList;
    }

    /**
     * 获取包前缀
     *
     * @param packageName 包名称
     * @return 包前缀名称
     */
    public static String getPackagePrefix(String packageName) {
        int lastIndex = packageName.lastIndexOf(".");
        return StringUtils.substring(packageName, 0, lastIndex);
    }


    /**
     * 获取权限前缀
     *
     * @param moduleName   模块名称
     * @param businessName 业务名称
     * @return 返回权限前缀
     */
    public static String getPermissionPrefix(String moduleName, String businessName) {
        return StrUtil.format("{}:{}", moduleName, businessName);
    }

}
